//
//  NHBaseTableTableViewController.m
//  LZNeiHan
//
//  Created by 梁梓烽 on 16/10/1.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "NHBaseTableViewController.h"
#import <objc/runtime.h>
#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import <Masonry.h>


#import "UIView+layer.h"
#import "UIView+Tap.h"
#import "NHBaseTableView.h"
#import "NHBaseTableViewCell.h"
#import <MJExtension.h>
#import "MJRefresh.h"
#import "NHBaseTableHeaderFooterView.h"


const char NHBaseTableVcNavRightItemHandleKey;
const char NHBaseTabelVcNavLeftItemHandleKey;

@interface NHBaseTableViewController ()
@property (nonatomic, copy) NHTableVcCellSelectedHandle handle;
@property(nonatomic,weak)UIImageView *refreshImg;
@end

@implementation NHBaseTableViewController
@synthesize  navItemTitle = _navItemTitle;
@synthesize navRightItem  = _navRightItem;
@synthesize  navLeftItem = _navLeftItem;
@synthesize needCellSepLine = _needCellSepLine;
@synthesize sepLineColor = _sepLineColor;
@synthesize tableEdgeInsets = _tableEdgeInsets;



#pragma mark -loading &alert
- (void)nh_showLoading {
    //    [FMHUD showLoading];
}

- (void)nh_hiddenLoading {
    //    [FMHUD hideHUD];
}

- (void)nh_showTitle:(NSString *)title after:(NSTimeInterval)after {
    //    [FDHUD showTitle:title];
    //    [FDHUD hideHUDAfterTimeout:after];
}

/** 添加空界面文字*/
- (void)nh_addEmptyPageWithText:(NSString *)text {
    //    [[NHEmptyPageManager sharedManager] setDelegateForScrollView:self.tableView emptyText:text];
}


/** 设置导航栏右边的item*/
-(void)nh_setUpNavRightItemTitle:(NSString *)itemTitle handle:(void (^)(NSString *))handle
{
    [self nh_setUpNavItemTitle:itemTitle handle:handle leftFrag:NO];
   
}
/** 设置导航栏左边的item */
-(void)nh_setUpNavLeftItemTitle:(NSString *)itemTitle handle:(void (^)(NSString *))handle
{
    [self nh_setUpNavItemTitle:itemTitle handle:handle leftFrag:YES];
}


-(void)nh_setUpNavItemTitle:(NSString *)itemTitle  handle:(void(^)(NSString *))handle  leftFrag:(BOOL)leftFrag
{
    if (itemTitle.length == 0|| !handle) {
        
        if (itemTitle == nil || [itemTitle isKindOfClass:[NSURL class]]) {
           itemTitle =@"";
        }
        
        if (leftFrag) {
            self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:nil action:nil];
        }
       else
       {
           self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:nil action:nil];
       }
    }
    
    else
    {
        if (leftFrag) {
            objc_setAssociatedObject(self,&NHBaseTabelVcNavLeftItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            
            self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:self action:@selector(clickBarbuttonItem:)];
        }
        else
        {
               objc_setAssociatedObject(self,&NHBaseTableVcNavRightItemHandleKey, handle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:itemTitle style:UIBarButtonItemStylePlain target:self action:@selector(clickBarbuttonItem:)];

        }
        
    }
}

/** 点击barbuttonitem相应的方法 */
-(void)clickBarbuttonItem:(UIBarButtonItem *)item
{
    void (^handle)(NSString * itemTitle) = objc_getAssociatedObject(self, &NHBaseTableVcNavRightItemHandleKey);
    if (handle) {
        handle(item.title);
    }
}


/** 监听通知 */
-(void)nh_observeNotiWithNotName:(NSString *)notName withAction:(SEL)action
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:action name:notName object:nil];
}

- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }


-(BOOL)prefersStatusBarHidden
{
    return  self.hiddenStatusBar;
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return self.barStyle;
}


/** 开始刷新图标的动画 */
-(void)startAnimation
{    CABasicAnimation *rotate = [[CABasicAnimation alloc]init];
    rotate.keyPath =@"transform.rotate.z";
    rotate.duration =1.5;
    rotate.toValue = [NSNumber numberWithFloat:M_PI *2];
    rotate.repeatCount = MAXFLOAT;
    rotate.cumulative = YES;

    [self.refreshImg.layer addAnimation:rotate forKey:@"refreshImgRotate"];
}

/** 结束刷新图标动画 */
-(void)endRefreshIconAnimation
{
    [self.refreshImg.layer removeAnimationForKey:@"refreshImgRotate"];
}

#pragma mark - 数据刷新相关
/** 刷新数据 */
-(void)nh_reloadData
{
    [self.tableview reloadData];
}

/** 下拉刷新*/
-(void)nh_refresh
{
    if (self.refreshType == NHBaseTableVcRefreshTypeNone || self.refreshType == NHBaseTableVcRefreshTypeOnlyCanLoadMore) {
        return ;
    }
    self.isRefresh = YES;
    self.isLoadMore = NO;
}

/** 上拉加载 */
-(void)nh_loadMore
{
    if (self.refreshType == NHBaseTableVcRefreshTypeNone || self.refreshType == NHBaseTableVcRefreshTypeOnlyCanRefresh) {
        return ;
    }
    if (self.dataArray.count == 0) {
        return ;
    }
    self.isRefresh = NO;
    self.isLoadMore = YES;

}

/** 开始下拉 */
-(void)nh_beginRefresh
{
if (self.refreshType == NHBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == NHBaseTableVcRefreshTypeRefreshAndLoadMore) {
    [NHUtils beginPulRefreshForScrollView:self.tableview];

    }
    
}

/** 停止下拉刷新 */
-(void)nh_endRefresh
{    if (self.refreshType == NHBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == NHBaseTableVcRefreshTypeRefreshAndLoadMore) {
    [NHUtils endRefreshForScrollView:self.tableview];
}
}

/** 停止上拉加载 */
-(void)nh_endLoadMore

{     if (self.refreshType == NHBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == NHBaseTableVcRefreshTypeRefreshAndLoadMore) {
    [NHUtils endLoadMoreForScrollView:self.tableview];
}
}

/** 隐藏heaeder刷新 */
-(void)nh_hiddenRefresh
{
    if (self.refreshType == NHBaseTableVcRefreshTypeOnlyCanRefresh || self.refreshType == NHBaseTableVcRefreshTypeRefreshAndLoadMore) {
    [NHUtils hiddenHeaderForScrollView:self.tableview];
    }
}

/** 隐藏上拉加载 */
-(void)nh_hiddenLoadMore
{
  if (self.refreshType == NHBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == NHBaseTableVcRefreshTypeRefreshAndLoadMore) {
    [NHUtils  hiddenFooterForScrollView:self.tableview];
    }
}

/** 提示没有更多信息*/
-(void)nh_noticeNoMoreData
{  if (self.refreshType == NHBaseTableVcRefreshTypeOnlyCanLoadMore || self.refreshType == NHBaseTableVcRefreshTypeRefreshAndLoadMore) {
    [NHUtils noticeNoMoreDataForScrollView:self.tableview];
}
}

/** 配置数据源 */
-(void)nh_commonConfigResponseWithRespose:(id)response  isRefresh:(BOOL)isRefresh  modelClass:(__unsafe_unretained Class)modelClass
{
    [self nh_commonConfigResponseWithResponse:response isRefresh:isRefresh modelClass:modelClass emptyText:nil];
}


/** 配置数据*/
- (void)nh_commonConfigResponseWithResponse:(id)response isRefresh:(BOOL)isRefresh modelClass:(__unsafe_unretained Class)modelClass emptyText:(NSString *)emptyText
{
    if ([response isKindOfClass:[NSArray class]] ==NO ) {
        return;
    }
    
    if (isRefresh) {
        //下拉刷新
        [self nh_endRefresh];
        
        [self.dataArray removeAllObjects];
        
        self.dataArray = [modelClass mj_objectArrayWithKeyValuesArray:response];
        
        // 设置空界面占位文字
        if (emptyText.length) {
            [self nh_addEmptyPageWithText:emptyText];
        }
        
        [self nh_reloadData];
        
    }
    
    else
    {
        //上拉加载
        [self nh_endLoadMore];
        
        if ([response count] == 0) {
            [self nh_noticeNoMoreData];
        }
        else
        {
            NSArray *newModels =[modelClass mj_objectArrayWithKeyValuesArray:response];
            
            if(newModels.count <50)
            {
                [self nh_hiddenLoadMore];
                
            }
            
            [self.dataArray addObjectsFromArray:newModels];
            
            // 刷新界面
            [self nh_reloadData];
        }
       
    }
}

/** 设置header刷新控件 */
-(void)nh_addRefresh
{
    [NHUtils addPullRefreshForScrollView:self.tableview pullRefreshCallBack:^{
          [self nh_refresh];
    }];
}

/** 设置footer刷新控件 */
-(void)nh_addLoadMore
{
    [NHUtils addLoadMoreForScrollView:self.tableview loadMoreCallBack:^{
        [self nh_loadMore];
    }];
    
}

-(BOOL)isHeaderFreshing
{
    
    return [NHUtils headerIsRefreshForScrollView:self.tableview];
}

-(BOOL)isFooterFreshing
{
    return [NHUtils footerIsRefreshForScrollView:self.tableview];
}


#pragma mark -view cycle
-(void)viewDidLoad
{
    [super viewDidLoad];
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tableview.frame  =self.view.bounds;
    [self.view  sendSubviewToBack:self.tableview];
}


#pragma mark -懒加载
/** 懒加载dataArray */
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray =[NSMutableArray new];
    }
    return _dataArray;
}

/** 加载tableview */
-(NHBaseTableView *)tableview
{
    if (!_tableview) {
        NHBaseTableView *tab = [[NHBaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [self.view addSubview:tab];
        _tableview = tab;
        tab.dataSource = self;
        tab.delegate = self;
        tab.backgroundColor = [UIColor colorWithRed:0.94f green:0.94f blue:0.94f alpha:1.00f];
        tab.separatorColor = kSeperatorColor;
    }
    
    return _tableview;
}


/** 刷新图标 */   //添加到tableviewcontroller的view的身上
-(UIImageView *)refreshImg
{
    if (!_refreshImg) {
        
        UIImageView *refreshImg = [[UIImageView alloc]init];
        [self.view addSubview:refreshImg];
        _refreshImg = refreshImg;
        refreshImg.image =[UIImage imageNamed:@"refresh"];
        refreshImg.layerCornerRadius = 22;
        refreshImg.backgroundColor =kWhiteColor;
        
        WeakSelf(weakSelf)
        
        [refreshImg makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.equalTo(weakSelf.view).offset(-15);
            make.size.equalTo(CGSizeMake(44, 44));
            make.bottom.equalTo(weakSelf.view).offset(-20);
            
        }];
        
        
        [refreshImg setTapActionWithBlock:^{
            
            [weakSelf startAnimation];
            [weakSelf nh_beginRefresh];
            
        }];
        
    }
    
    return _refreshImg;
    
}


#pragma mark - 属性的set get方法
- (UIView *)refreshHeader {
    return self.tableview.mj_header;
}

/** statusBar是否隐藏 */
-(void)setHiddenStatusBar:(BOOL)hiddenStatusBar
{
    _hiddenStatusBar = hiddenStatusBar;
    
    [self setNeedsStatusBarAppearanceUpdate];
}

/** statusBar样式 */
-(void)setBarStyle:(UIStatusBarStyle)barStyle
{
    if (_barStyle == barStyle) return;
    _barStyle =barStyle ;
    [self setNeedsStatusBarAppearanceUpdate];
    
}

/** 设置是否显示刷新icon */
-(void)setShowRefreshIcon:(BOOL)showRefreshIcon
{
    _showRefreshIcon =showRefreshIcon;
    
    self.refreshImg.hidden = !showRefreshIcon;
}

/** 设置刷新类型 */

-(void)setRefreshType:(NHBaseTableVcRefreshType)refreshType
{
    _refreshType =refreshType;
    
    switch (refreshType) {
        case NHBaseTableVcRefreshTypeNone:  //没有刷新
            break;
            
        case NHBaseTableVcRefreshTypeOnlyCanLoadMore: //上拉加载
        {
            [self nh_addLoadMore];
        }
            break;
            
        case NHBaseTableVcRefreshTypeOnlyCanRefresh: //下拉加载
        {
            [self nh_addRefresh];
        }
            break;
            
        case NHBaseTableVcRefreshTypeRefreshAndLoadMore: //能刷新
        {
            [self nh_addRefresh];
            [self nh_addLoadMore];
        }
            break;
        default:
            break;
    }
}

/** 导航栏标题 */
-(void)setNavItemTitle:(NSString *)navItemTitle
{
    if ([navItemTitle isKindOfClass:[NSString class]] == NO|| [navItemTitle isEqualToString:navItemTitle]) {
        return;
    }
    
    _navItemTitle =navItemTitle;
    
    self.navigationItem.title = navItemTitle;
}

-(NSString *)navItemTitle
{
    return self.navigationItem.title;
}


-(void)setNavRightItem:(UIBarButtonItem *)navRightItem
{
    _navRightItem =navRightItem;
    
    self.navigationItem.rightBarButtonItem = navRightItem;
    
}

-(UIBarButtonItem *)navRightItem
{
    return self.navigationItem.rightBarButtonItem;
}


-(void)setNavLeftItem:(UIBarButtonItem *)navLeftItem
{
    _navLeftItem = navLeftItem;
    self.navigationItem.leftBarButtonItem = navLeftItem;
}


-(UIBarButtonItem *)navLeftItem
{
    return self.navigationItem.leftBarButtonItem;
}


-(void)setNeedCellSepLine:(BOOL)needCellSepLine
{
    _needCellSepLine = needCellSepLine;
    
    self.tableview.separatorStyle = needCellSepLine? UITableViewCellSeparatorStyleSingleLine :UITableViewCellSeparatorStyleNone;
}


-(BOOL)needCellSepLine
{
    
    return  self.tableview.separatorStyle ==UITableViewCellSeparatorStyleSingleLine;
   
}


-(void)setSepLineColor:(UIColor *)sepLineColor
{
    _sepLineColor = sepLineColor ;
    
    self.tableview.separatorColor = sepLineColor;
}

-(UIColor *)sepLineColor
{
    return self.tableview.separatorColor;
    
}


-(void)setTableEdgeInsets:(UIEdgeInsets)tableEdgeInsets
{
    _tableEdgeInsets =tableEdgeInsets;
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    [self.view setNeedsLayout];
}


#pragma mark -<UItableviewDelegate UItableviewDataSource>
/** 多少组 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self respondsToSelector:@selector(nh_numberOfSections)]) {
        [self nh_numberOfSections];
    }
    return 0;
}

/** 组里面多少行 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self respondsToSelector:@selector(nh_numberOfRowsInSection:)]) {
        [self nh_numberOfRowsInSection:section];
    }
    return 0;
}

/** 每个cell的内容 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    if ([self respondsToSelector:@selector(nh_cellAtIndexPath:)]) {
        [self nh_cellAtIndexPath:indexPath];
    }
    
    //1.创建cell
    NHBaseTableViewCell *cell   =[NHBaseTableViewCell cellWithTableView:self.tableview];
    //2.返回cell
    return cell;
    

}

/** 每个cell即将显示在屏幕上 */
- (void)tableVifew:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.needCellSepLine) return;
    
    UIEdgeInsets edgeInsets  = UIEdgeInsetsMake(0, 15, 0, 0);
    
    if ([self respondsToSelector:@selector(nh_sepEdgeInsetsAtIndexPath:)]) {
        [self nh_sepEdgeInsetsAtIndexPath:indexPath];
    }
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])  [tableView setSeparatorInset:edgeInsets];
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) [tableView setLayoutMargins:edgeInsets];
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) [cell setSeparatorInset:edgeInsets];
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) [cell setLayoutMargins:edgeInsets];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self respondsToSelector:@selector(nh_cellHeightAtIndexPath:)]) {
        [self nh_cellHeightAtIndexPath:indexPath];
    }
    
    return 0.01;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self  respondsToSelector:@selector(nh_sectionHeaderHeightAtSection:)]) {
        [self nh_sectionHeaderHeightAtSection:section];
    }
    return 0.01;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ([self respondsToSelector:@selector(nh_sectionFooterHeightAtSection:)]) {
        [self nh_sectionFooterHeightAtSection:section];
    }
    return 0.01;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if ([self respondsToSelector: @selector(nh_headerAtSection: )]) {
        [self nh_headerAtSection:section];
    }
    return nil;
    
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ([self respondsToSelector:@selector(nh_footerAtSection:)]) {
        [self nh_footerAtSection:section];
    }
    return nil;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NHBaseTableViewCell  *cell  = [tableView cellForRowAtIndexPath:indexPath];
    
    if ([self respondsToSelector:@selector(nh_didSelectCellAtIndexPath:)]) {
        [self nh_didSelectCellAtIndexPath:indexPath];
    }
    
}

#pragma mark -子类去重写
/** 分组数量 */
-(NSInteger)nh_numberOfSections{ return  0;}

/** 某个分组的cell数量 */
-(NSInteger)nh_numberOfRowsInSection:(NSInteger)section{ return  0;}

/** 某行的cell */

-(NHBaseTableViewCell *)nh_cellAtIndexPath:(NSIndexPath *)indexPath{
    return [NHBaseTableViewCell cellWithTableView:self.tableview];
}

/** 点击某行*/
-(void)nh_didSelectCellAtIndexPath:(NSIndexPath *)indexPath{}

/** 某行行高 */
-(CGFloat)nh_cellHeightAtIndexPath:(NSIndexPath *)indexPath{ return 0; }

/** 某个组头 */
-(UIView *) nh_headerAtSection:(NSInteger)section
{
    return [NHBaseTableHeaderFooterView headerFooterViewWithTableView:self.tableview];
}

/** 某个组尾 */
-(UIView *) nh_footerAtSection:(NSInteger)section
{
    return  [NHBaseTableHeaderFooterView headerFooterViewWithTableView:self.tableview];
}

/** 某个组头高度 */
-(CGFloat)nh_sectionHeaderHeightAtSection:(NSInteger)section { return 0.01; }

/** 某个组尾的高度 */
-(CGFloat)nh_sectionFooterHeightAtSection:(NSInteger)section { return 0.01; }

/** 分割线偏移*/
-(UIEdgeInsets)nh_sepEdgeInsetsAtIndexPath:(NSIndexPath *)indexPath{ return UIEdgeInsetsMake(0, 15, 0, 0); }





@end
